/*  Author: Sublime Porte <sublime@sublimeporte.info>    *
 *  License: GPL v3                                      *
 *  Usage: textview <filename>                           *
 *  Description: A very simple text viewer/editor.       *
 *               Designed to be quick over full featured *
 *  compile with: valac --pkg gtk+-2.0 textview.vala     */

using Gtk;
using Gdk;

public class MainWin : Gtk.Window {
	private string openFile;
	private TextView txtView;
	private Label statusBar;
	
	public MainWin(string fileName) {
		this.default_height = 600; 
        this.default_width = 700;
        this.window_position = WindowPosition.CENTER;
        this.title = "textview - " + fileName;
        
        txtView = new TextView();
        txtView.editable = false;
        txtView.set_wrap_mode(Gtk.WrapMode.WORD);
        txtView.key_press_event.connect(on_key_press_event);
        var scrollWin = new ScrolledWindow(null, null);
        scrollWin.add(txtView);
        
        this.statusBar = new Label("");
        this.statusBar.xalign = 0;
        
        var vbox = new VBox (false, 0);
        vbox.add (scrollWin);
        vbox.pack_start (this.statusBar, false, true, 0);
        this.add (vbox);
        
		this.LoadFile(fileName);
	}
	
	private void LoadFile(string fileName) {
		openFile = fileName;
		string text;
		try {
            FileUtils.get_contents(fileName, out text);
            txtView.buffer.set_text(text);
            statusBar.label = "Successfully loaded: " + fileName;
        } catch (FileError ex) {            
			if (ex.code == 4) {
				statusBar.label = "File does not exist, will be created on save";
			}
		}
        
	}
	
	private void SaveFile() {
		try {
			Gtk.TextIter start, end;
			txtView.buffer.get_start_iter(out start);
			txtView.buffer.get_end_iter(out end);
            FileUtils.set_contents (openFile, txtView.buffer.get_text(start, end, false)); 
            statusBar.label = "Saved file: " + openFile;
        } catch (FileError ex) {
            statusBar.label = "Error saving: " + ex.message;
        }
	}
	
	private bool on_key_press_event(EventKey eKey) {
		string key = Gdk.keyval_name(eKey.keyval);

		switch (key) {
		case "Escape":
			if (txtView.get_editable()) {
				txtView.set_editable(false);
				statusBar.label = "Entered command mode!";
			} else {
				txtView.set_editable(true);
				statusBar.label = "Entered edit mode!";
			}
		break;
		case "w":
			if (!txtView.get_editable()) {
				SaveFile();
			}
			break;
		}
		return false;
	}
	
	public static int main (string[] args) {
		Gtk.init(ref args);
		if (args.length != 2) {
			print("Usage: textview <filename>\n");
			return 1;
		}
		var app = new MainWin(args[1]);
		app.show_all();
		app.destroy.connect(Gtk.main_quit);
		Gtk.main();
		return 0;
	}
}
